package com.sumainfor.zuul.controller.provider;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.sumainfor.common.util.CustomMap;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.ObjectUtil;
import com.sumainfor.zuul.entity.*;
import com.sumainfor.zuul.service.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author PuaChen
 * @Create 2018-11-08 15:05
 */
@RestController
@RequestMapping("/provider")
@Log4j2
public class UserProviderController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysAreaDeptService areaDeptService;

    @Autowired
    private SysAreaService areaService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @PostMapping("/getUser")
    public JsonResult getUserInfo(@RequestBody List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return JsonResult.error("参数错误");
        }
        List<Map<String, Object>> user = userService.getUserById(ids);
        return JsonResult.success(user);
    }

    @GetMapping("/getUserByRepairsId")
    public JsonResult getUserByRepairsId(@RequestParam List<String> ids) {
        return JsonResult.success("查询成功");
    }

    /**
     * 通过用户的ID 获取用户所在的服务中心编号
     *
     * @param userId
     * @return
     */
    @PostMapping("/getCenterServiceInfo")
    public JsonResult getCenterServiceInfo(String userId) {
        if (StringUtils.isBlank(userId)) {
            return JsonResult.errorForEmpty();
        }
        SysUserEntity userEntity = userService.selectById(userId);
        if (userEntity == null) {
            return JsonResult.actionFailure();
        }
        SysDeptEntity entity = deptService.selectById(userEntity.getDeptId());
        if (entity == null) {
            return JsonResult.actionFailure();
        }
        Integer id = getCenter(entity);
        if (id == null) {
            return JsonResult.actionFailure();
        }
        return JsonResult.success(id);
    }

    public Integer getCenter(SysDeptEntity child) {

        if (child.getType() == 3) {
            return child.getDeptId();
        }

        if (child.getParentId() <= 0) {
            return null;
        }
        SysDeptEntity entity = deptService.selectById(child.getParentId());
        if (entity == null) {
            return null;
        }
        return getCenter(entity);
    }


    /**
     * 获取所有的维修师傅角色的用户信息
     *
     * @return
     */
    @PostMapping("/selectRepairPeople")
    public List<Map<String, Object>> selectRepairPeople(String name) {
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("role_name", "维修师傅");
        List<SysRoleEntity> roleList = roleService.selectList(wrapper);
        List<Map<String, Object>> data = Lists.newArrayList();

        for (SysRoleEntity roleEntity : roleList) {
            wrapper = new EntityWrapper();
            wrapper.eq("role_id", roleEntity.getRoleId());
            List<SysUserRoleEntity> list = userRoleService.selectList(wrapper);
            for (SysUserRoleEntity userRoleEntity : list) {
                wrapper = new EntityWrapper();
                wrapper.eq("user_id", userRoleEntity.getUserId());
                SysUserEntity userEntity = userService.selectOne(wrapper);
                if (StringUtils.isNotBlank(name)) {
                    if (userEntity.getName().contains(name)) {
                        data.add(CustomMap.create("userName", userEntity.getName())
                                .put("userId", userEntity.getUserId()));
                    }
                } else {
                    data.add(CustomMap.create("userName", userEntity.getName())
                            .put("userId", userEntity.getUserId()));
                }
            }
        }
        return data;
    }

    /**
     * 获取服务中心 部门数据通过ID
     *
     * @param deptId
     * @return
     */
    @PostMapping("/getDeptInfoById")
    public Map<String, Object> getDeptInfoById(String deptId) {
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("dept_id", deptId);
        SysDeptEntity sysDeptEntity = deptService.selectOne(wrapper);
        return ObjectUtil.convertObjectToMap(sysDeptEntity);
    }


    /**
     * 获取这个部门的所属公司信息
     *
     * @param deptId
     * @return
     */
    @PostMapping("/getAreaInfoForGSByDeptId")
    public JsonResult getAreaInfoForGSByDeptId(String deptId) {
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("dept_id", deptId);
        List<SysAreaDeptEntity> list = areaDeptService.selectList(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return JsonResult.error("没有绑定公司");
        }
        wrapper = new EntityWrapper();
        wrapper.eq("type", 1);
        wrapper.in("area_id", list.stream().map(item -> item.getAreaId()).collect(Collectors.toList()));
        List<SysAreaEntity> areaList = areaService.selectList(wrapper);
        log.info("getAreaInfoForGSByDeptId areaList ==>{}", areaList);
        SysAreaEntity entity = areaList.get(0);
        return JsonResult.success(eachGetTopAreaInfo(entity.getAreaId()));
    }


    private SysAreaEntity eachGetTopAreaInfo(Integer areaId) {
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("area_id", areaId);
        SysAreaEntity entity = areaService.selectOne(wrapper);
        if (entity != null && entity.getParentId() != null) {
            SysAreaEntity areaEntity = eachGetTopAreaInfo(entity.getParentId());
            if (areaEntity == null) {
                return entity;
            }
        }
        return entity;
    }


    /**
     * 获取服务中心编号集合 通过公司编号
     *
     * @param areaId
     * @return
     */
    @PostMapping("/getCenterServiceIdList")
    public List<Map<String, Object>> getCenterServiceIdList(Integer areaId) {
        List<Map<String, Object>> data = Lists.newArrayList();
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq(areaId != null, "area_id", areaId);
        List<Map<String, Object>> list = areaDeptService.selectMaps(wrapper);
        for (Map<String, Object> entity : list) {
            wrapper = new EntityWrapper();
            wrapper.eq("dept_id", MapUtils.getString(entity, "deptId"));
            wrapper.eq("`type`", 3);
            SysDeptEntity one = deptService.selectOne(wrapper);
            if (one == null) {
                wrapper = new EntityWrapper();
                wrapper.eq("area_id", MapUtils.getString(entity, "areaId"));
                wrapper.eq("dept_id", MapUtils.getString(entity, "deptId"));
                areaDeptService.delete(wrapper);
                continue;
            }
            data.add(CustomMap.create("id", one.getDeptId()).put("name", one.getName()));
        }
        return CustomMap.removeRepeatMapByKey(data, "id");
    }

    /**
     * 查询这个部门下的人员数量 服务中心编号
     *
     * @param deptId
     * @return
     */
    @PostMapping("/getPeopleCountByDeptId")
    public Integer getPeopleCountByDeptId(Integer deptId, String startTime, String endTime) {
        List<Integer> deptIds = Lists.newArrayList(deptId);
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("parent_id", deptId);
        List<SysDeptEntity> list = deptService.selectList(wrapper);
        for (SysDeptEntity entity : list) {
            deptIds.add(entity.getDeptId());
        }
        int count = userService.selectCountForPeople(startTime, endTime, deptIds);
        return count;
    }

    /**
     * 查询人员信息数据 带分页
     *
     * @param size
     * @param current
     * @param miId
     * @param startTime
     * @param endTime
     * @return
     */
    @PostMapping("/selectPeopleData")
    public Page<Map<String, Object>> selectPeopleData(Integer size, Integer current, Integer miId, String startTime, String endTime) {
        List<Integer> deptIds = Lists.newArrayList(miId);
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("parent_id", miId);
        List<SysDeptEntity> list = deptService.selectList(wrapper);
        for (SysDeptEntity entity : list) {
            deptIds.add(entity.getDeptId());
        }
        if (CollectionUtils.isEmpty(deptIds)) {
            deptIds = null;
        }
        Page page = new Page(current, size);
        List<Map<String, Object>> data = userService.selectPeopleForData(page, startTime, endTime, deptIds);
        page.setRecords(data);
        return page;
    }

    /**
     * 根据用户姓名模糊查询用户信息
     *
     * @param username
     * @return
     */
    @PostMapping("/searchUserForName")
    public JsonResult searchUserForName(String username) {
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.like("name", username);
        List<SysUserEntity> list = userService.selectList(wrapper);
        return JsonResult.success(list);
    }

}
